/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 *
 */

import path from 'path';

import { expect } from '@jest/globals';
import fse from 'fs-extra';

import { initExecuteCommand, runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRoot = project.projectRootPath();
  const hvigorLog = path.resolve(projectRoot, '.hvigor/outputs/build-logs/build.log');

  const commands = initExecuteCommand({
    mode: 'module',
    product: 'default',
    tasks: 'assembleHap',
  });
  const commands1 = initExecuteCommand({
    mode: 'project',
    product: 'default',
    tasks: 'assembleApp',
  });

  // 先执行完两个命令后再一起检查
  const result = await runHvigorAsync(projectRoot, commands);
  const result1 = await runHvigorAsync(projectRoot, commands1);

  record.addStep('构建后查看build.log文件中的bundleName字段，已匿名', result);
  const logFileBuff = await fse.readFile(hvigorLog);
  const logFile = logFileBuff.toString().split(/\r?\n/);

  logFile.forEach((str) => {
    if (/\s*bundleName: '/.test(str)) {
      expect(str).not.toContain('.');
    }
  });

  record.addStep('检查所有report文件的bundleName', result1);
  const reportDirPath = path.resolve(projectRoot, './.hvigor/report');
  const reportPaths = fse.readdirSync(reportDirPath);
  for (const reportPath of reportPaths) {
    const reportBuff = await fse.readFile(path.resolve(reportDirPath, reportPath));
    const reportStr = reportBuff.toString();
    if (reportStr.indexOf('bundleName') !== -1) {
      expect(reportStr).toMatch(/bundleName: '.\*{3}.'/g);
    }
  }
};

TestCaseBuilder.builder()
  .caseName('DTS2024101503741')
  // eslint-disable-next-line max-len
  .description('【DevEco Studio】【开发自提单】【安全】【单框架】【API14】AR20241011939513 IDE日志回传需求，bundleName匿名化处理')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testfun)
  .load();
